package com.dayu.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.dayu.finecomm.pojo.DeviceConfig;
import com.dayu.utils.PropertiesUtil;
import com.dayu.web.param.BaseConfigParam;
import com.dayu.web.param.TokenParam;
import com.dayu.web.service.ConfigService;
import com.dayu.web.utils.YamlUtil;
import com.dayu.web.vo.RESTResponse;

/**
 * 基本配置类
 * 
 * @author Chenjiawei
 *
 *         2017年5月24日
 */
@Controller
@RequestMapping("/unitalk/v1.0")
public class ConfigCtrl {

	static Logger LOGGER = LoggerFactory.getLogger(ConfigCtrl.class);

	@Resource
	ConfigService configService;

	/**
	 * 获取基础配置
	 */
	@ResponseBody
	@RequestMapping(value = "/baseconfig.json", method = RequestMethod.POST)
	public String getBaseConfigs(@RequestBody TokenParam token) {

		if (PropertiesUtil.exists() && YamlUtil.isExist()) {

			BaseConfigParam param = configService.getBaseConfigs();

			return RESTResponse.of(param).toString();
		} else {
			return RESTResponse.of(1, "获取基础配置失败!").toString();
		}

	}

	/**
	 * 修改基础配置
	 */
	@ResponseBody
	@RequestMapping(value = "/baseconfig/update.json", method = RequestMethod.POST)
	public String updateBaseConfigs(@RequestBody BaseConfigParam param) {

		LOGGER.info(JSON.toJSONString(param));

		if (PropertiesUtil.exists() && YamlUtil.isExist()) {

			PropertiesUtil.setProperty("service.finecomm.server.tcp.port",
					param.getServerPort() + "");
			PropertiesUtil.setProperty("service.finecomm.server.tcp.host",
					param.getServerIp());

			List<String> protocols = new ArrayList<String>();
			protocols.addAll(param.getProtocols());
			List<DeviceConfig> list = configService.updateBaseConfigs(
					param.getDest(), protocols);

			Map<String, List<DeviceConfig>> map = new HashMap<String, List<DeviceConfig>>();
			map.put("finecomms", list);

			YamlUtil.setProper(map);

			return RESTResponse.of(0, "修改基础配置成功!").toString();
		} else {
			return RESTResponse.of(1, "修改基础配置失败!").toString();
		}

	}
}
